import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:garbage_classification/global.dart';
import 'package:garbage_classification/main_manager.dart';
import 'package:garbage_classification/utils/request.dart';
import 'package:provider/provider.dart';

class ResultPage extends StatefulWidget {
  ResultPage({Key key, this.keyword = ""}) : super(key: key);
  final String keyword;
  @override
  _ResultPageState createState() => _ResultPageState();
}

class _ResultPageState extends State<ResultPage> {
  bool showLoading = false;
  TextEditingController _searchController = new TextEditingController();
  Map _data = {
    "keyword": "",
    "recommended": "",
    "all": "none",
    "catpicList": [""]
  };

  @override
  void initState() {
    if (widget.keyword != "") searchKey(widget.keyword);
    super.initState();
  }

  void searchKey(String keyword) async {
    showLoading = true;
    try {
      var res = await search(keyword);
      setState(() {
        String _str = json.encode(res);
        _data = json.decode(_str);
      });
      showLoading = false;
    } catch (e) {
      showLoading = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    MainManager mainManager = Provider.of<MainManager>(context);
    return Scaffold(
      body: showLoading
          ? Center(child: CircularProgressIndicator())
          : Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.only(top: Global.paddingTop),
                    width: MediaQuery.of(context).size.width,
                    decoration: BoxDecoration(
                      color: Global.mainColor,
                    ),
                    child: Row(
                      children: [
                        InkWell(
                          onTap: () => {Navigator.pop(context)},
                          child: Container(
                            width: 50,
                            height: 50,
                            child: Icon(
                              Icons.arrow_back_ios,
                              color: Global.backgroundColor,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Global.backgroundColor.withOpacity(0.3),
                              borderRadius: BorderRadius.circular(2),
                            ),
                            child: TextField(
                              controller: _searchController,
                              keyboardType: TextInputType.text,
                              // autofocus: true,
                              decoration: InputDecoration.collapsed(
                                hintText: "请输入需要查询的垃圾名称",
                                hintStyle: TextStyle(
                                  color: Global.backgroundColor,
                                  fontSize: 13,
                                ),
                              ),
                              onSubmitted: (text) {
                                if (text != "") {
                                  searchKey(text);
                                  if (!mainManager.historyList.contains(text)) {
                                    mainManager.historyList.insert(0, text);
                                    mainManager.update(
                                        history: mainManager.historyList);
                                  }
                                }
                              },
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            if (_searchController.text.toString() != "") {
                              var str = _searchController.text.toString();
                              searchKey(str);
                              if (!mainManager.historyList.contains(str)) {
                                mainManager.historyList.insert(0, str);
                                mainManager.update(
                                    history: mainManager.historyList);
                              }
                            }
                          },
                          child: Container(
                            width: 50,
                            height: 50,
                            child: Icon(
                              Icons.search,
                              color: Global.backgroundColor,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  _data['all'] == ""
                      ? Container(
                          height: 300,
                          child: Center(
                              child: Text(
                            "我已经知道啦,还没来得及分类，请稍后再试试吧！",
                            style: TextStyle(color: Global.fontSecondColor),
                          )))
                      : Container(),
                  Expanded(
                    child: _data['keyword'] != "" && _data['all'] != ""
                        ? SingleChildScrollView(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                SizedBox(height: 20),
                                Center(
                                  child: Text(
                                    _data['keyword'],
                                    style: TextStyle(
                                      color: Global.mainColor,
                                      fontSize: 20,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                                SizedBox(height: 20),
                                _data['catpicList'].length < 1
                                    ? Container()
                                    : Center(
                                        child: Image.network(
                                          _data['catpicList'][0],
                                          width: MediaQuery.of(context)
                                                  .size
                                                  .width /
                                              2,
                                        ),
                                      ),
                                _data['catpicList'].length < 2
                                    ? Container()
                                    : Center(
                                        child: Image.network(
                                          _data['catpicList'][1],
                                          width: MediaQuery.of(context)
                                                  .size
                                                  .width /
                                              2,
                                        ),
                                      ),
                                SizedBox(height: 10),
                                Center(
                                  child: Text(
                                    "其他分类名称：${_data['all']}",
                                    style: TextStyle(
                                      color: Global.fontColor,
                                      fontSize: 15,
                                    ),
                                  ),
                                ),
                                SizedBox(height: 10),
                                Container(
                                  decoration: BoxDecoration(
                                    color: Color(0xFFffd57e),
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  width: MediaQuery.of(context).size.width,
                                  margin: EdgeInsets.all(10),
                                  padding: EdgeInsets.all(10),
                                  child: Text(
                                    "爱护环境人人有责！本分类以上海垃圾分类为标准，其他城市基本也都分为四类，知识名词叫法略有不同而已。 垃圾主要为：1、可回收垃圾，2、湿垃圾(厨余垃圾,餐厨垃圾,易腐垃圾)，3、干垃圾(其他垃圾)，4、有害垃圾",
                                    style: TextStyle(
                                      color: Global.backgroundColor,
                                    ),
                                  ),
                                )
                              ],
                            ),
                          )
                        : Container(),
                  ),
                ],
              ),
            ),
    );
  }
}
